<template>
  <div class="device-maintenance-modal" v-if="visible" @click.self="closeModal">
    <div class="modal-content">
      <div class="modal-header">
        <h2>设备资源维护</h2>
        <button class="close-btn" @click="closeModal">×</button>
      </div>
      
      <div class="modal-body">
        <div class="device-categories">
          <!-- 试验中心设备 -->
          <div class="category-section">
            <div class="category-header">
              <h3>试验中心</h3>
              <button class="add-device-btn" @click="addDevice('test_center')">
                + 添加设备
              </button>
            </div>
            
            <div class="device-table">
              <div class="table-header">
                <div class="col-name">设备名称</div>
                <div class="col-quantity">数量</div>
                <div class="col-single-capacity">单设备容量</div>
                <div class="col-capacity">总设备容量</div>
                <div class="col-actions">操作</div>
              </div>
              
              <div class="table-body">
                <div 
                  v-for="device in testCenterDevices" 
                  :key="device.id"
                  class="device-row"
                >
                  <div class="col-name">
                    <input 
                      v-model="device.name" 
                      class="device-input"
                      placeholder="请输入设备名称"
                      @input="markAsModified(device)"
                    />
                  </div>
                  <div class="col-quantity">
                    <input 
                      v-model.number="device.quantity" 
                      type="number" 
                      class="device-input"
                      min="1"
                      @input="markAsModified(device)"
                    />
                  </div>
                  <div class="col-single-capacity">
                    <input 
                      v-model.number="device.singleCapacity" 
                      type="number" 
                      class="device-input"
                      min="1"
                      @input="markAsModified(device)"
                    />
                  </div>
                  <div class="col-capacity">
                    <input 
                      v-model.number="device.capacity" 
                      type="number" 
                      class="device-input readonly-input"
                      min="1"
                      readonly
                    />
                  </div>
                  <div class="col-actions">
                    <button 
                      class="action-btn delete-btn" 
                      @click="deleteDevice(device.id, 'test_center')"
                      title="删除"
                    >
                      🗑️
                    </button>
                  </div>
                </div>
                
                <div v-if="testCenterDevices.length === 0" class="empty-row">
                  暂无设备，点击上方"添加设备"按钮添加
                </div>
              </div>
            </div>
          </div>
          
          <!-- 总装&机构展开设备 -->
          <div class="category-section">
            <div class="category-header">
              <h3>总装&机构展开</h3>
              <button class="add-device-btn" @click="addDevice('assembly')">
                + 添加设备
              </button>
            </div>
            
            <div class="device-table">
              <div class="table-header">
                <div class="col-name">设备名称</div>
                <div class="col-quantity">数量</div>
                <div class="col-single-capacity">单设备容量</div>
                <div class="col-capacity">总设备容量</div>
                <div class="col-actions">操作</div>
              </div>
              
              <div class="table-body">
                <div 
                  v-for="device in assemblyDevices" 
                  :key="device.id"
                  class="device-row"
                >
                  <div class="col-name">
                    <input 
                      v-model="device.name" 
                      class="device-input"
                      placeholder="请输入设备名称"
                      @input="markAsModified(device)"
                    />
                  </div>
                  <div class="col-quantity">
                    <input 
                      v-model.number="device.quantity" 
                      type="number" 
                      class="device-input"
                      min="1"
                      @input="markAsModified(device)"
                    />
                  </div>
                  <div class="col-single-capacity">
                    <input 
                      v-model.number="device.singleCapacity" 
                      type="number" 
                      class="device-input"
                      min="1"
                      @input="markAsModified(device)"
                    />
                  </div>
                  <div class="col-capacity">
                    <input 
                      v-model.number="device.capacity" 
                      type="number" 
                      class="device-input readonly-input"
                      min="1"
                      readonly
                    />
                  </div>
                  <div class="col-actions">
                    <button 
                      class="action-btn delete-btn" 
                      @click="deleteDevice(device.id, 'assembly')"
                      title="删除"
                    >
                      🗑️
                    </button>
                  </div>
                </div>
                
                <div v-if="assemblyDevices.length === 0" class="empty-row">
                  暂无设备，点击上方"添加设备"按钮添加
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="modal-footer">
        <button class="btn btn-secondary" @click="closeModal" :disabled="loading">取消</button>
        <button class="btn btn-primary" @click="saveDevices" :disabled="loading">
          {{ loading ? '保存中...' : '保存' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'DeviceResourceMaintenance',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      testCenterDevices: [],
      assemblyDevices: [],
      nextId: 1,
      loading: false,
      baseURL: '/api/equipment/'
    }
  },
  methods: {
    closeModal() {
      this.$emit('close')
    },
    
    addDevice(category) {
      const newDevice = {
        id: `temp_${Date.now()}`, // 临时ID，保存时会被后端分配真实ID
        name: '',
        quantity: 1,
        singleCapacity: 1,
        capacity: 1, // 初始值，会被自动计算覆盖
        organization: category === 'test_center' ? '试验中心' : '总装&机构展开',
        isNew: true // 标记为新设备
      }
      
      // 计算总设备容量
      this.calculateCapacity(newDevice)
      
      if (category === 'test_center') {
        this.testCenterDevices.push(newDevice)
      } else if (category === 'assembly') {
        this.assemblyDevices.push(newDevice)
      }
    },
    
    async deleteDevice(deviceId, category) {
      if (!confirm('确定要删除这个设备吗？')) {
        return
      }
      
      try {
        this.loading = true
        
        // 如果是新设备（还未保存到数据库），直接从本地删除
        if (typeof deviceId === 'string' && deviceId.startsWith('temp_')) {
          if (category === 'test_center') {
            this.testCenterDevices = this.testCenterDevices.filter(d => d.id !== deviceId)
          } else if (category === 'assembly') {
            this.assemblyDevices = this.assemblyDevices.filter(d => d.id !== deviceId)
          }
          return
        }
        
        // 删除数据库中的设备
        await axios.delete(`${this.baseURL}${deviceId}/`)
        
        // 从本地列表中移除
        if (category === 'test_center') {
          this.testCenterDevices = this.testCenterDevices.filter(d => d.id !== deviceId)
        } else if (category === 'assembly') {
          this.assemblyDevices = this.assemblyDevices.filter(d => d.id !== deviceId)
        }
      } catch (error) {
        console.error('删除设备失败:', error)
        alert('删除设备失败，请重试')
      } finally {
        this.loading = false
      }
    },
    
    async saveDevices() {
      // 验证设备名称不能为空
      const allDevices = [...this.testCenterDevices, ...this.assemblyDevices]
      const hasEmptyName = allDevices.some(device => !device.name.trim())
      
      if (hasEmptyName) {
        alert('请填写所有设备的名称')
        return
      }
      
      try {
        this.loading = true
        
        // 分离新设备和已存在的设备
        const newDevices = allDevices.filter(device => device.isNew)
        const existingDevices = allDevices.filter(device => !device.isNew)
        
        // 批量创建新设备
        if (newDevices.length > 0) {
          const createData = newDevices.map(device => ({
            organization: device.organization,
            device_name: device.name,
            device_quantity: device.quantity,
            single_device_capacity: device.singleCapacity,
            device_capacity: device.capacity
          }))
          
          await axios.post(`${this.baseURL}batch_create/`, {
            equipment_list: createData
          })
        }
        
        // 更新已存在的设备
        for (const device of existingDevices) {
          if (device.modified) {
            await axios.put(`${this.baseURL}${device.id}/`, {
              organization: device.organization,
              device_name: device.name,
              device_quantity: device.quantity,
              single_device_capacity: device.singleCapacity,
              device_capacity: device.capacity
            })
          }
        }
        
        // 保存成功后立即关闭界面，并传递设备数据
        const deviceData = {
          testCenter: this.testCenterDevices,
          assembly: this.assemblyDevices
        }
        this.$emit('save', deviceData)
        this.closeModal()
        
        // 在后台重新加载数据，不影响界面关闭
        this.loadDevices().catch(error => {
          console.error('重新加载数据失败:', error)
        })
      } catch (error) {
        console.error('保存设备数据失败:', error)
        console.error('错误详情:', error.response?.data)
        console.error('错误状态:', error.response?.status)
        alert(`保存失败：${error.response?.data?.message || error.message || '请重试'}`)
      } finally {
        this.loading = false
      }
    },
    
    async loadDevices() {
      try {
        this.loading = true
        const response = await axios.get(this.baseURL)
        
        if (response.data.success) {
          const devices = response.data.data
          
          // 按组织分类设备
          this.testCenterDevices = devices
            .filter(device => device.organization === '试验中心')
            .map(device => {
              const deviceObj = {
                id: device.id,
                name: device.device_name,
                quantity: device.device_quantity,
                singleCapacity: device.single_device_capacity,
                capacity: device.device_capacity,
                organization: device.organization,
                isNew: false
              }
              // 重新计算总设备容量以确保数据一致性
              this.calculateCapacity(deviceObj)
              return deviceObj
            })
          
          this.assemblyDevices = devices
            .filter(device => device.organization === '总装&机构展开')
            .map(device => {
              const deviceObj = {
                id: device.id,
                name: device.device_name,
                quantity: device.device_quantity,
                singleCapacity: device.single_device_capacity,
                capacity: device.device_capacity,
                organization: device.organization,
                isNew: false
              }
              // 重新计算总设备容量以确保数据一致性
              this.calculateCapacity(deviceObj)
              return deviceObj
            })
        } else {
          this.initializeDefaultData()
        }
      } catch (error) {
        console.error('加载设备数据失败:', error)
        alert('无法连接到后端服务器，请确保后端服务正在运行')
        // 如果加载失败，使用默认数据
        this.initializeDefaultData()
      } finally {
        this.loading = false
      }
    },
    
    initializeDefaultData() {
      this.testCenterDevices = []
      this.assemblyDevices = []
    },
    
    // 监听设备数据变化，标记为已修改
    markAsModified(device) {
      if (!device.isNew) {
        device.modified = true
      }
      // 当数量或单设备容量改变时，重新计算总设备容量
      this.calculateCapacity(device)
    },
    
    // 计算总设备容量
    calculateCapacity(device) {
      device.capacity = device.quantity * device.singleCapacity
    }
  },
  
  mounted() {
    // 组件挂载时从数据库加载数据
    this.loadDevices()
  },
  
  watch: {
    visible(newVal) {
      if (newVal) {
        // 每次打开模态框时重新加载数据
        this.loadDevices()
      }
    }
  }
}
</script>

<style scoped>
.device-maintenance-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 1200px;
  max-height: 90%;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.close-btn:hover {
  background: #f8f9fa;
  color: #333;
}

.modal-body {
  flex: 1;
  padding: 24px;
  overflow: hidden;
  min-height: 500px;
}

.device-categories {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  height: 100%;
}

.category-section {
  border: 1px solid #e9ecef;
  border-radius: 6px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
  max-height: 500px;
}

.category-header {
  background: #f8f9fa;
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e9ecef;
}

.category-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.add-device-btn {
  background: #28a745;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.add-device-btn:hover {
  background: #218838;
}

.device-table {
  background: white;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-header {
  display: grid;
  grid-template-columns: 2fr 1fr 1.2fr 1.5fr 80px;
  gap: 16px;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  font-weight: 600;
  color: #555;
  font-size: 14px;
}

.table-body {
  min-height: 60px;
  max-height: 400px;
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
}

/* 自定义滚动条样式 */
.table-body::-webkit-scrollbar {
  width: 6px;
}

.table-body::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.table-body::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.table-body::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.device-row {
  display: grid;
  grid-template-columns: 2fr 1fr 1.2fr 1.5fr 80px;
  gap: 16px;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  align-items: center;
}

.device-row:last-child {
  border-bottom: none;
}

.device-row:hover {
  background: #f8f9fa;
}

.device-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.device-input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.readonly-input {
  background-color: #f8f9fa !important;
  color: #6c757d !important;
  cursor: not-allowed !important;
}

.readonly-input:focus {
  border-color: #ddd !important;
  box-shadow: none !important;
}

.col-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: all 0.2s;
}

.delete-btn {
  background: #dc3545;
  color: white;
}

.delete-btn:hover {
  background: #c82333;
  transform: translateY(-1px);
}

.empty-row {
  padding: 40px 20px;
  text-align: center;
  color: #666;
  font-style: italic;
}

.modal-footer {
  padding: 20px 24px;
  border-top: 1px solid #e9ecef;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #5a6268;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover {
  background: #0056b3;
}

@media (max-width: 768px) {
  .modal-content {
    width: 95%;
    margin: 20px;
  }
  
  .device-categories {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .table-header,
  .device-row {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .col-actions {
    justify-content: flex-start;
  }
  
  .modal-body {
    min-height: 400px;
  }
}
</style>